<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import publicFormConfig from "./config";
import { FormInst } from "naive-ui";
import getBASE64 from "@/utils/lib/upload";
import uploadIcon from "@/assets/icons/upload.png";
import { formatDate } from "@/utils/lib/date";
import { useUserStore } from "@/store/modules/user";
import { status } from "@/enums/thingEnum";
import router from "@/router";
import { getThingType, publicThing } from "@/api/thing";


const userStore = useUserStore();

const formRef = ref<FormInst | null>();
const imageInputRef = ref();
let imageURL = ref<string>("");

const pageData = reactive({
  type: [],
  init: false
})

// 文件上传，触发input的change事件
const uploadFile = () => {
  imageInputRef.value.click();
};

// 上传文件
const handleFile = async (e) => {
  let file = e.target.files[0];
  console.log(file);

  if (!file) {
    return;
  }
  const BASE64 = await getBASE64(file);
  imageURL.value = BASE64 as string;
};

// 取消
const cancel = () => {
  router.replace('/thing/index')
};

// 确定
const confirm = async () => {
  try {
    const instance: Record<string, any> = formRef?.value?.getFormRef();
    // console.log(instance.model);
    // console.log(userStore);

    instance.validate(async (err) => {
      if (!err) {
        let data = {
          img: imageURL.value,
          TIME: formatDate(new Date()),
          status_id:
            status[instance.model.tag === "寻物启事" ? "正在寻找" : "等待认领"],
          user_id: userStore.info.user_id,
          audit_status: "未审核",
          is_delete: 0,
          ...instance.model,
        };
        console.log(data);
        if (data.img === "") {
          window.$message.warning("请上传图片");
          return;
        }
        await publicThing(data);
        router.replace('/thing/index')

        formRef?.value?.reset();
        imageURL.value = "";
      } else {
        window.$message.error("发布失败");
      }
    });
  } catch (error) {
    return Promise.reject(error);
  }
};

/**
 * 获取启事类别
 */
const getType = async () => {
  try {
    const res = await getThingType()
    if (res.data.code === 200) {
      pageData.type = res.data.data
    }
  } catch (error) {
    return Promise.reject(error)
  }
}

watch(() => pageData.init, (val) => {
  if (val) {
    publicFormConfig.formItems[1].options = pageData.type.map((item:Record<string,any>) => {
      return {
        label: item.TYPE,
        value:item.id
      }
    })
  }

})

const init = async () => {
  try {
    await getType()
    pageData.init = true
  } catch (error) {
    return Promise.reject(error)
  }
}
init()

</script>

<template>
  <div class="public-box" v-if="pageData.init">
    <div class="title-box">
      <p class="title">发布</p>
    </div>
    <div class="form">
      <Form :config="publicFormConfig" ref="formRef" />
      <div class="img-box">
        <p class="name">图片 <span>*</span></p>
        <div class="img" @click="uploadFile">
          <n-image v-if="imageURL" width="95" height="95" :src="imageURL" lazy preview-disabled />
          <div v-else class="icon-box">
            <p class="icon-title">点击上传</p>
            <n-image width="20" height="20" :src="uploadIcon" lazy preview-disabled />
          </div>
        </div>
        <input type="file" name="" id="" class="file-input" accept="image/*" ref="imageInputRef" @change="handleFile" />
      </div>
      <div class="btns">
        <n-space>
          <n-button @click="cancel" class="btn" strong secondary type="tertiary">取消</n-button>
          <n-button @click="confirm" strong secondary type="info" class="btn">确定</n-button>
        </n-space>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
@import "@/styles/mixin.less";

.public-box {
  border: 1px solid #ccc;

  // height: 500px;
  .title-box {
    height: 50px;
    border-bottom: 1px solid #ccc;
    .flex(row, flex-start, center);

    .title {
      color: rgb(3, 180, 170);
      font-size: 20px;
      font-weight: bold;
      margin-left: 15px;
    }
  }

  .form {
    padding: 20px 30px;

    .img-box {
      .name {
        font-weight: bold;

        span {
          color: #d03050;
        }
      }

      .img {
        margin-top: 10px;
        width: 100px;
        height: 100px;
        border: 2px dotted #ccc;
        background-color: rgb(250, 250, 252);
        .flex(row, center, center);
        cursor: pointer;

        p {
          font-size: 20px;
        }

        &:hover {
          border: 2px dotted green;
        }

        .icon-box {
          .flex(column, center, center);

          .icon-title {
            font-size: 14px;
            color: #666;
          }
        }
      }

      .file-input {
        display: none;
      }
    }

    .btns {
      .flex(row, flex-end, center);
    }
  }
}
</style>
